(function($) {
           

    var imgRotationCache = [];
   
	$.fn.spreadPhotos = function(){		
		
		jQuery.each($('#imgWrapper').children(), function(index, value){
			imgRotationCache.push($(value).css(('-moz-transform')));
		});
		
		$(this).bind("click.fanOutImgs",function(){
			$.fn.fanOutPhotos();	
		});
			
	};
	
	$.fn.setupArea = function(){

		$(this).mouseenter(function(){
			$.fn.fanOutPhotos();
		});

        $(this).mouseleave(function(){
			$.fn.gatherAllImg(); 
			$(this).hidePreview();
		});

	}

     
	
    $.fn.bottomStackImageByZindex = function(){
    	
    	var orderedImg = [];
    	var bottomStackImg = $('#imgWrapper img');
    	
    	for(var i = 0; i < bottomStackImg.length ; i++){
    		    		
    		var zindex = $(bottomStackImg[i]).css("z-index");    		
    		orderedImg[zindex] = $(bottomStackImg[i]);
    		
    	}
    	
    	return orderedImg.reverse();
    }
    
    $.fn.spreadAllPhotos = function(){
		
		$("#imgWrapper img").addClass('spreadedImg');
		$(this).spread($.fn.bottomStackImageByZindex(), imgRotationCache,5);

		$.fn.resetEvents();

		$(this).initReStack();
    }

    $.fn.fanOutPhotos = function(){
		    	    	
		var bottomStackImg = $.fn.bottomStackImageByZindex();
		var imgToGather = $('.spreadedImg');		
		var imgToSpread = [];			
		var spreadedImgCnt = 0;
		
		for(var stackIndex = 0; stackIndex < bottomStackImg.length && spreadedImgCnt < 4; stackIndex++)
		{
						
			if(bottomStackImg[stackIndex].hasClass('.spreadedImg'))
			{
				continue;
			}
			
			imgToSpread.push(bottomStackImg[stackIndex]);
			$(bottomStackImg[stackIndex]).addClass('spreadedImg');
			spreadedImgCnt += 1;
			
		}
		
		 
		$(this).spread(imgToSpread,imgRotationCache,2);
		
		
		if(imgToGather.length > 0)
		{
			var gatherPos = {leftPos: 70, topPos: 70};
			$(this).gather(imgToGather,gatherPos);
		}
	};

	

	$.fn.gatherAllImg = function(){
	       
        $(this).gather($('.spreadedImg'),{leftPos: 450, topPos: 300});
        $(".spreadedImg").removeClass("spreadedImg");      
        $.fn.resetEvents();
        $('#imgWrapper').spreadPhotos();
        $('#stackInstruction').fadeOut();

    }; 	 

    $.fn.resetEvents = function (){
    	$("#imgWrapper img").unbind("click.changeOrderEvent");  	    
        $('#imgWrapper').unbind("click.fanOutImgs");
    };

})(jQuery);


